﻿using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common
{
    public class Fallback : DemoBase
    {
        public override string DemoName => "Polly-Fallback Demo";

        /// <summary>
        /// 全局动态调整时长
        /// </summary>
        private int _timeout = 1;
        public override void RunDemo()
        {
            base.Init();

            var mainPolicy = Policy.Handle<Exception>()
                    .Fallback(() =>
                    {
                        _timeout++;
                        PrintErrorLog($"数据量太大 调整超时时间：{_timeout} 秒");
                    });
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    mainPolicy.Execute(RequestFromWeb);
                }
            }
            catch (Exception e)
            {
                PrintError($"异常：{e.GetType().Name},{e.Message}");
            }
        }

        private void RequestFromWeb()
        {
            if (_timeout < 5)
            {
                PrintLog("开始请求数据包");
                Thread.Sleep(_timeout * 1000);
                throw new WebException("请求超时");
            }
            else
            {
                PrintLog("开始请求数据包");
                Thread.Sleep(_timeout * 1000);
                PrintSuccessLog("请求数据包成功");
                _timeout = 3;//模拟网络状态变化
            }
        }
    }
}
